package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result senCode(String phone, HttpSession session) {
        //1.校验手机号
        if (check_phone(phone)) {
            return Result.fail(PHONE_REG_FAIL);
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.发送验证码
        log.info("发送验证码成功：code{}",code);
        //3.保存验证码到redis
        stringRedisTemplate.opsForValue().set(MESSAGE_CODE_PREFIX+phone,code,MESSAGE_CODE_EXPIRE, TimeUnit.MINUTES);
        //4.返回结果
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (phone==null||check_phone(phone)) {
            return Result.fail(PHONE_REG_FAIL);
        }
        //2.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(MESSAGE_CODE_PREFIX + phone);
        String code = loginForm.getCode();
        if(code==null||!cacheCode.equals(code)){
            return Result.fail(MESSAGE_CODE_ERR);
        }
        //2.查询用户并判断用户是否存在
        User user = query().eq("phone", phone).one();
        if(user==null){
            user = new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(8));
            save(user);
        }
        //分离出部分数据节省内存
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //3.保存用户到redis
        //3.1将用户数据封装为map存入redis节省内存空间、方便字段修改
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),CopyOptions.create()
                .setIgnoreNullValue(true).setFieldValueEditor((fieldName,field)->{
                    return field.toString();
                }));
        //3.2存入redis
        //3.2.1生成token写回前端
        String token = UUID.randomUUID().toString(true);
        log.debug("token:"+token);
        stringRedisTemplate.opsForHash().putAll(USER_TOKEN_PREFIX+token,map);
        //3.3设置有效期
        stringRedisTemplate.expire(USER_TOKEN_PREFIX+token,TOKEN_EXPIRE,TimeUnit.MINUTES);
        //4.返回结果
        return Result.ok(token);
    }

    @Override
    public Result me() {
        return Result.ok(UserHolder.getUser());
    }

    @Override
    public Result sign() {
        //获得当前用户
        UserDTO user = UserHolder.getUser();
        //拼接出该用户签到key
        LocalDateTime now = LocalDateTime.now();
        String key=user.getId()+":sign:"+now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //计算出今天是本月的多少天
        int dayOfMonth = now.getDayOfMonth();
        //向redis存入签到标识
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result continueCount() {
        //获取当前用户
        UserDTO user = UserHolder.getUser();
        //拼接出该用户签到key
        LocalDateTime now = LocalDateTime.now();
        String key=user.getId()+":sign:"+now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //计算出今天是本月的多少天
        int dayOfMonth = now.getDayOfMonth();
        //获得该用户所有统计数据 十进制数
        List<Long> datas = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                .valueAt(0));
        //没有签到记录
        if(datas==null||datas.isEmpty())return Result.ok(0);
        Long data = datas.get(0);
        //从后往前循环遍历十进制转二进制的每一位 统计连续签到结果
        int count=0;
        while (true){
            if((data&1)==0){
                break;
            }else {
                ++count;
            }
            data >>>=1;
        }
        return Result.ok(count);
    }

    private boolean check_phone(String phone){
       return RegexUtils.isPhoneInvalid(phone);
    }
}
